# -*- coding: utf-8 -*-

from flask import Flask
import os

app = Flask(__name__)
profile = os.environ.get('DANTE_PROFILE', '')
app.config.from_object('config.' + profile + 'Config')

import pymysql
pymysql.install_as_MySQLdb()

import logging
from logging import Formatter
from logging.handlers import TimedRotatingFileHandler
from dante.database import db_session
from dante.views import general

@app.teardown_request
def remove_db_session(exception):
  db_session.remove()

def init_logger():
  logger = logging.getLogger('Dante')
  handler = TimedRotatingFileHandler(app.config['LOG_FILE'], when="midnight")
  handler.suffix = '%Y-%m-%d'
  handler.setFormatter(Formatter(
    '%(asctime)s %(module)s %(levelname)s: %(message)s '
    '[in %(pathname)s:%(lineno)d]'
  ))
  app.logger.addHandler(handler)
  app.logger.setLevel(logging.INFO)
  logger.addHandler(handler)
  logger.setLevel(logging.INFO)

init_logger()

app.logger.info('Dante is using profile: [{0}]'.format(app.config['PROFILE']))

app.register_blueprint(general.mod)

import datetime
import pickle
import pytz
import redis
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.jobstores.redis import RedisJobStore
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor

rdb = app.config['REDIS_APS_DB']
rhost = app.config['REDIS_HOST']
rport = app.config['REDIS_PORT']
rpass = app.config['REDIS_PASSWORD']

jobstores = {
    'redis': RedisJobStore(db=rdb, jobs_key='apscheduler.jobs', run_times_key='apscheduler.run_times', pickle_protocol=pickle.HIGHEST_PROTOCOL, host = rhost, password = rpass, port = rport)
}
executors = {
    'default': ThreadPoolExecutor(20),
    'processpool': ProcessPoolExecutor(5)
}
job_defaults = {
    'coalesce': False,
    'max_instances': 3
}
tz=pytz.timezone('Asia/Shanghai')
scheduler = BackgroundScheduler(jobstores=jobstores, executors=executors, job_defaults=job_defaults, timezone=tz)
scheduler.start()
app.logger.info('Dante Redis Job Store Started. [{0}:{1}/{2}]'.format(rhost, rport, rdb))

from rq import Queue
rqdb = app.config['REDIS_QUEUE_DB']
r = redis.Redis(host = rhost, port = rport, password = rpass, db = rqdb)
scheduler_q = Queue('high',connection = r)
immediate_q = Queue('normal',connection = r)
app.logger.info('Dante Redis Queue Started. HIGH and NORMAL')